from monster import Monster1,Monster2,BaseMonster
from player import Player
from  overlay import Overlay
from sprites import Generic, Water
from settings import *
from pytmx.util_pygame import  load_pygame
import random

from support import *


class Level:
    def __init__(self):
        # 获取显示surface
        self.display_surface = pygame.display.get_surface()

        # 精灵组
        self.all_sprites = CameraGroup()
        self.collisoin_sprites = pygame.sprite.Group()
        self.monster_sprites = pygame.sprite.Group()
        
        self.setup()
        self.overlay = Overlay(self.player)
        
        # 怪物生成相关
        self.monster_spawn_time = 0
        self.monster_spawn_interval = 2.0  # 每3秒尝试生成一次怪物
        self.max_monsters = 50  # 最大怪物数量
        
        # 保存对 Game 实例的引用
        self.game = None
    #防御性编程      
    def set_game(self, game):
        """设置对 Game 实例的引用"""
        self.game = game
        # 让玩家也能访问到 Level 实例，使用 level_instance 而不是 level
        self.player.level_instance = self

    #加载所有东西
    def setup(self):
        tmx_data = load_pygame('../mygame/data/map.tmx')

      
        
        # 围栏
        for x, y, surf in tmx_data.get_layer_by_name('Fence').tiles():
            Generic((x * TILE_SIZE, y * TILE_SIZE), surf, [self.all_sprites, self.collisoin_sprites])
        
        # water
        water_frames = import_folder('../mygame/graphics/water')
        for x, y, surf in tmx_data.get_layer_by_name('Water').tiles():
            Water((x * TILE_SIZE, y * TILE_SIZE), water_frames, self.all_sprites)

        # Player
        for obj in tmx_data.get_layer_by_name('Player'):
            if obj.name == 'Start':
                self.player = Player(
                    pos=(obj.x, obj.y),
                    group=self.all_sprites,
                    collision_sprites=self.collisoin_sprites,
                    monster_sprites=self.monster_sprites
                )

                #self.monster1 = Monster1(pos=(obj.x, obj.y - 600), group=[self.all_sprites, self.monster_sprites], player=self.player)

        Generic(
            pos=(0,0),
            surf=pygame.image.load('../mygame/graphics/world/ground.png').convert_alpha(),
            groups=self.all_sprites,
            z=LAYERS['ground']
        )




    def spawn_monster(self, dt):
        # 添加时间累加器
        self.monster_spawn_time += dt
        
        # 清理已经死亡的怪物
        for monster in self.monster_sprites.sprites():
            if monster.health <= 0:
                monster.kill()
        
        # 打印调试信息
       
        
        if self.monster_spawn_time >= self.monster_spawn_interval and len(self.monster_sprites) < self.max_monsters:
            #print("尝试生成新怪物...")
            self.monster_spawn_time = 0  # 重置计时器
            
            # 尝试最多10次找到合适的生成位置
            for _ in range(10):
                random_x = random.randint(0, TILE_WID_NUMBER * TILE_SIZE)
                random_y = random.randint(0, TILE_HEI_NUMBER * TILE_SIZE)
                
                spawn_pos = pygame.math.Vector2(random_x, random_y)
                player_pos = pygame.math.Vector2(self.player.rect.center)
                
                # 检查与玩家的距离（不要太近）
                if (spawn_pos - player_pos).magnitude() < 500:
                    continue
                    
                # 检查是否与碍物重叠
                temp_rect = pygame.Rect(random_x - 32, random_y - 32, 64, 64)
                collision = False
                for sprite in self.collisoin_sprites:
                    if sprite.rect.colliderect(temp_rect):
                        collision = True
                        break
                        
                if not collision:
                    #print("成功生成新怪物!")
                    if random.random() < 0.5:
                        Monster1(pos=(random_x, random_y), 
                                group=[self.all_sprites, self.monster_sprites], 
                                player=self.player)
                    else:
                        Monster2(pos=(random_x, random_y), 
                                group=[self.all_sprites, self.monster_sprites], 
                                player=self.player)
                    break

    def run(self, dt):
        self.monster_spawn_time += dt  # 确保在run方法中更新时间
        self.spawn_monster(dt)
        self.all_sprites.custom_draw(self.player)
        self.all_sprites.update(dt)
        self.overlay.display()
        
       # print(self.player.itme_inventory)
#重点的相机类
class CameraGroup(pygame.sprite.Group):
    def __init__(self):
        super().__init__()
        self.display_surface = pygame.display.get_surface()
        self.offset = pygame.math.Vector2()
        self.debug_mode = True  # 添加调试模式标志

    def custom_draw(self, player):
        # 获取偏移量
        self.offset.x = player.rect.centerx - SCREEN_WIDTH / 2
        self.offset.y = player.rect.centery - SCREEN_HEIGHT / 2

        # 按层级和Y坐标排序绘制精灵
        for layer in LAYERS.values():
            for sprite in sorted(self.sprites(), key=lambda sprite: sprite.rect.centery):
                if sprite.z == layer:
                    # 绘制精灵
                    offset_rect = sprite.rect.copy()
                    offset_rect.center -= self.offset
                    self.display_surface.blit(sprite.image, offset_rect)

                    # 调试模式：绘制hitbox
                    if self.debug_mode and hasattr(sprite, 'hitbox'):
                        hitbox_rect = sprite.hitbox.copy()
                        hitbox_rect.center -= self.offset
                        
                        # 为不同类型的精灵使用不同颜色
                        if isinstance(sprite, Player):
                            pygame.draw.rect(self.display_surface, (0, 255, 0), hitbox_rect, 2)  # 玩家 - 绿色
                        elif isinstance(sprite, BaseMonster):
                            pygame.draw.rect(self.display_surface, (255, 0, 0), hitbox_rect, 2)  # 怪物 - 红色
                        else:
                            pygame.draw.rect(self.display_surface, (255, 255, 0), hitbox_rect, 2)  # 其他 - 黄色

        # 绘制玩家的攻击范围（如果正在攻击）
        if hasattr(player, 'attack_points') and hasattr(player, 'attack_display_time'):
            current_time = pygame.time.get_ticks()
            if current_time - player.attack_display_time < 350:  # 攻击动画持续时间
                # 调整攻击范围点的位置以适应相机偏移
                adjusted_points = [(x - self.offset.x, y - self.offset.y) for x, y in player.attack_points]
                # 绘制攻击范围 - 蓝色
                pygame.draw.polygon(self.display_surface, (0, 0, 255), adjusted_points, 2)

        # 绘制怪物血条
        for sprite in self.sprites():
            if isinstance(sprite, BaseMonster):
                sprite.draw_hp_bar(self.display_surface, self.offset)

